from flask import Flask, jsonify, request
from flask_cors import CORS
import json
from sqlalchemy import create_engine, Column, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import re
engine = create_engine('sqlite:///DataBase/Main.db', echo=True)
Base = declarative_base()
Session = sessionmaker(bind=engine)
session = Session()
Base.metadata.create_all(engine)

class TreeJson(Base):
    __tablename__ = 'tree_json'
    id = Column(String, primary_key=True)
    tree_json_path = Column(String)

    def __repr__(self):
        return "<TreeJson(name='%s', path='%s')>" % (self.name, self.path)

def addTreeJson(id, time, path=r"DataBase\\TreeJson\\"):
    new_tree_json = TreeJson(id=id, tree_json_path=path+str(time)+".json")
    session.add(new_tree_json)
    session.commit()

def showAllTreeJson():
    for tree_json in session.query(TreeJson).all():
        print(tree_json.id, tree_json.tree_json_path)

app = Flask(__name__)
CORS(app, resources={
    r"/": {
        "origins": "*",
    }
})

@app.route('/', methods=['GET'])
def get_tree_json():
    # 处理GET请求
    url = request.args.get('url')
    print(f"Received GET request: {url}")
    tree_node = session.query(TreeJson).filter_by(id=url).first()
    path = tree_node.tree_json_path if tree_node else None
    if path:
        print(path, "success")
        with open(path, "r", encoding="utf-8") as f:
            response_data = f.read()
        return response_data
    else:
        return jsonify({"error": "No matching record found"})

@app.route('/', methods=['POST'])
def post_tree_json():
    # 处理POST请求
    try:
        data = request.json
        url = data.get('url')
        print(f"Received POST request: {url}")
        showAllTreeJson()
        tree_node = session.query(TreeJson).filter_by(id=url).first()
        if not tree_node:
            print("No matching record found")
        path = tree_node.tree_json_path if tree_node else None
        print(path)
        tree_json_path="/www/wwwroot/default/"+path
        parts = text.split('/')
        match_str = parts[1]
        edge_path="/www/wwwroot/default/"+ path.replace(match_str,"EdgeJson")
        node_path="/www/wwwroot/default/"+ path.replace(match_str,"NodeJson")
        if tree_json_path:
            with open(tree_json_path,"r",encoding="utf-8") as f:
                tree_json=f.read()
            with open(edge_path,"r",encoding="utf-8") as f:
                edge_json=f.read()
            with open(node_path,"r",encoding="utf-8") as f:
                node_json=f.read()
            print(jsonify({"mindmap_data":tree_json,"edge_data":edge_json,"node_data":node_json}))
            return jsonify({"mindmap_data":tree_json,"edge_data":edge_json,"node_data":node_json})
        else:
            return jsonify({"error": "No matching record found"})
    except Exception as e:
        return jsonify({"error": str(e)})

if __name__ == '__main__':
    # 用你的证书和私钥替换下面的路径
    ssl_cert = '/www/wwwroot/default/certificate.crt'
    ssl_key = '/www/wwwroot/default/private.key'
    
    app.run(host="0.0.0.0",port=8080,ssl_context=(ssl_cert, ssl_key),debug=False)